package lambdasinaction.chap10;

import java.util.*;

import static java.util.stream.Collectors.toSet;

public class OptionalMain {

    public static void main(String... args){
        Insurance insurance = new Insurance();
        Optional<Insurance> optionalInsurance = Optional.of(insurance);


        Car car = new Car(optionalInsurance);
        Optional<Car> optionalCar = Optional.of(car);


        Person person = new Person(optionalCar);
        Optional<Person> optionalPerson = Optional.of(person);


        String carInsuranceName = getCarInsuranceName(optionalPerson);
        System.out.println(carInsuranceName);


        //没有合适的则返回默认值
        Optional<Insurance> cheapestInsurance = nullSafeFindCheapestInsurance(optionalPerson, optionalCar);
        System.out.println(cheapestInsurance.map(Insurance::getName).orElse("没有合适的保险"));







        //没有合适的则抛出异常
        try{
            cheapestInsurance.map(Insurance::getName).
                    orElseThrow(() -> new Exception("没有找到合适的保险"));
        }catch (Exception e){
            System.out.println(e);
        }



    }




    public static String getCarInsuranceName(Optional<Person> person) {
        return person.flatMap(Person::getCar)
                     .flatMap(Car::getInsurance)
                     .map(Insurance::getName)
                     .orElse("Unknown");
    }


    /**
     *
     * @return
     */
    public static Optional<Insurance> nullSafeFindCheapestInsurance(Optional<Person> person ,Optional<Car> car){
        return person.flatMap(p -> car.map( c -> findCheapestInsurance(p,c)));
    }


    public static Insurance findCheapestInsurance(Person person ,Car car){
        return new Insurance();
    }






    public static Set<String> getCarInsuranceNames(List<Person> persons) {
        return persons.stream()
                      .map(Person::getCar)
                      .map(optCar -> optCar.flatMap(Car::getInsurance))
                      .map(optInsurance -> optInsurance.map(Insurance::getName))
                      .flatMap(Optional::stream)
                      .collect(toSet());
    }
}
